
from CommonCar import *
# import networkx as nx
import math
from beaconmessage import *


carObjList = []

simulatTimePara = 1

class ThreadDealMain(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        mainDeal(simulatTimePara)


def getDistance(a1,b1,a2,b2):

    dis = math.sqrt((a1-a2) ** 2 + (b1-b2) ** 2) 
    
    dis = round(dis,3)

    return dis



def mainDeal(simuTime):

    b1 = BeaconMessage(1,1,1,1,1,0,0,0,0,0,0,100,5,10)  #构造一个广播消息
    b2 = BeaconMessage(2,0,0,4,5,0,0,0,0,0,0,100,5,10)  #构造一个广播消息
    b3 = BeaconMessage(3,0,-10,-20,5,0,0,0,0,0,0,100,5,10)  #构造一个广播消息   

    car1 = CommonCar()
    car1.setBeacon(b1.getBeacon())
    car2 = CommonCar()
    car2.setBeacon(b2.getBeacon())
    car3 = CommonCar()
    car3.setBeacon(b3.getBeacon())
    
    carObjList.append(car1)  
    carObjList.append(car2) 
    carObjList.append(car3) 


    totalTime = simuTime # 仿真时间按秒计算

    tempDir = {}
    while True:
        try:

            for broadCastObj in carObjList:

                selfTempDir = broadCastObj.broadCast()

                tempList = []  #用于存储复合条件的邻居车辆

                tempList.append(selfTempDir)

                for revObj in carObjList:

                    if revObj != broadCastObj:

                        neberTempDir = {}
                        neberTempDir = revObj.broadCast()

                        if getDistance(selfTempDir['x'],selfTempDir['y'],neberTempDir['x'],neberTempDir['y']) < selfTempDir['range']: # 根据车辆的范围判断是否在邻居队列里

                            tempList.append(neberTempDir)

                broadCastObj.updateNeberList(tempList.copy())
                tempList.clear()

            totalTime -= 1
            time.sleep(1)  # 延时1s

            if totalTime == 0 :
                return 1

        except Exception as e:
            print(e)
            return 0



if __name__ == '__main__':

    threadOne = ThreadDealMain()
    threadOne.start()